package com.ego.item.service;

import com.ego.common.PageResult;
import com.ego.item.mapper.SkuMapper;
import com.ego.item.mapper.SpuDetailMapper;
import com.ego.item.mapper.SpuMapper;
import com.ego.item.mapper.StockMapper;
import com.ego.item.pojo.Brand;
import com.ego.item.pojo.Category;
import com.ego.item.pojo.Spu;
import com.ego.item.pojo.SpuDetail;
import com.ego.item.vo.SpuVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoogsServiceImpl implements GoogsService{
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    /**
     * 分页查询商品信息
     * @param key       关键字
     * @param saleable  是否上架，0：下架  1：上架
     * @param page      当前页
     * @param rows      每页显示数量
     * @return
     */
    @Override
    public PageResult<SpuVo> page(String key, Boolean saleable, Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //1,关键字查询,标题/子标题关键字模糊查询
        if (StringUtils.isNoneBlank(key)){
            criteria.andLike("title", "%"+key+"%").orLike("subTitle", "%"+key+"%");
        }
        //2,上下架状态查询
        criteria.andEqualTo("saleable", saleable);

        //3,排序方式，根据创建日期降序  必须写字段名
        example.setOrderByClause("create_time desc");
        //使用spuMapper查询商品信息
        Page<Spu> items = (Page<Spu>) spuMapper.selectByExample(example);
        //将spu转换为spuVo  stream()做数据转换
        List<SpuVo> spuVoList = items.getResult().stream().map(spu -> {
            SpuVo spuVo = new SpuVo();
            //将spu中的属性值拷贝到spuvo中去
            BeanUtils.copyProperties(spu, spuVo);

            //根据类别&品牌id查询出对应的名字
            //根据类别ids查询类别信息
            List<Long> cids = Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3());
            List<Category> categoryList = categoryService.findListByCids(cids);
            //将categoryList转换为xx/yy/zz这种形式的String格式显示在前端
            List<String> categoryNames =
                    categoryList.stream().map(category -> category.getName()).collect(Collectors.toList());
            //使用工具将类别信息用"/"拼接起来
            spuVo.setCategoryName(StringUtils.join(categoryNames,"/"));
            //根据id获取品牌信息
            Brand brand = brandService.findByBid(spu.getBrandId());
            spuVo.setBrandName(brand.getName());
            return spuVo;
        }).collect(Collectors.toList());
        return new PageResult<>(items.getTotal(),spuVoList);
    }

    @Override
    public void deleteById(Long id) {
        spuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(SpuVo spuVo) {
        //1,添加spu
        spuMapper.insertSelective(spuVo);


        //2,添加spu_detail
        SpuDetail spuDetail = spuVo.getSpuDetail();
        spuDetail.setSpuId(spuVo.getId());
        spuDetailMapper.insertSelective(spuDetail);

        //3,添加sku&stock
        if (spuVo.getSkus()!=null&spuVo.getSkus().size()>0){
            spuVo.getSkus().forEach(sku -> {
                sku.setCreateTime(spuVo.getCreateTime());
                sku.setSpuId(spuVo.getId());
                skuMapper.insertSelective(sku);
                sku.getStock().setSkuId(sku.getId());
                stockMapper.insertSelective(sku.getStock());
            });
        }
    }
}
